package com.sdp.irrigation.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.irrigation.cache.IrrigationCleanCache;
import com.sdp.irrigation.db.irrigation_eq.service.IIrrigationEqService;
import com.sdp.irrigation.db.irrigation_eq_type.service.IIrrigationEqTypeService;
import com.sdp.irrigation.entity.IrrigationEq;
import com.sdp.irrigation.entity.IrrigationEqType;

/**
 * <p>
 * 设备类型 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2025-03-01
 */
@RestController
@RequestMapping("/IrrigationEqTypeController")
public class IrrigationEqTypeController {
	
	@Autowired
	private IIrrigationEqTypeService iIrrigationEqTypeService;
	
	@Autowired
	private IIrrigationEqService iIrrigationEqService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private IrrigationCleanCache irrigationEqTypeController;
	

	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iIrrigationEqTypeService, IrrigationEqType.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody IrrigationEqType eqType) {
		if(eqType==null) {
			return Result.error("设备类型信息为空");
		}
		if(StringUtils.isEmpty(eqType.getKeyId())) {
			eqType.setCreateTime(LocalDateTime.now());
			eqType.setUpdateTime(LocalDateTime.now());
			iIrrigationEqTypeService.save(eqType);
		}else {
			eqType.setUpdateTime(LocalDateTime.now());
			iIrrigationEqTypeService.updateById(eqType);
		}
		irrigationEqTypeController.cleanEqType();
		return Result.ok();
	}
	

	@GetMapping(value="/queryEqTypeByEqNo")
	public Result<?> queryEqTypeByEqNo(@RequestParam(name="eqNo",required=true) String eqNo) {
		IrrigationEq eq = iIrrigationEqService.queryEqByEqNo(eqNo);
		if(StringUtils.isEmpty(eq)) {
			return Result.error("此设备不存");
		}
		if(StringUtils.isEmpty(eq.getEqType())) {
			return Result.error("此设备未设置设备类型");
		}
		
		IrrigationEqType eqType = iIrrigationEqTypeService.queryEqTypeByTypeCode(eq.getEqType());
		if(StringUtils.isEmpty(eqType)) {
			return Result.error("此设备设置的设备类型不存");
		}
		return Result.ok(eqType);
	}

}

